import 'dart:io';

import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:dio/dio.dart';

import '../../global/xmm_apis.dart';
import '../../utils/xmm_platform_utils.dart';
import '../log/xmm_logcat.dart';

class XmmLogInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    XmmXLogcat.d(
        "http REQUEST->url=${options.path},params=${options.queryParameters}");
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    XmmXLogcat.d(
        "http RESPONSE->url=${response.requestOptions.path},data=${response.data}");
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    XmmXLogcat.d("http ERROR->url=${err.requestOptions.path},err=${err.error}");
    super.onError(err, handler);
  }
}

class ParamInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    Map<String, dynamic> headers = options.headers;
    headers['device-id'] = XmmPlatformUtils.deviceId ?? ""; // 设备id或者udid，保证当前设备唯一值。
    if (Platform.isAndroid) {
      headers['platform'] = 'Android';
    } else if (Platform.isIOS) {
      headers["platform"] = "iOS";
    }
    headers['model'] = XmmPlatformUtils.model; // 设备型号
    headers['pkg'] = XmmPlatformUtils.packageName; // 包名
    headers['ver'] = XmmPlatformUtils.appVersionName; // 版本 例如1.0.0，读取实际配置的版本号
    headers['p_ver'] = XmmPlatformUtils.appVersionCode; // build number
    headers['kst'] = '1'; // 固定传1
    headers['sys_lan'] = XmmPlatformUtils.systemLanguage; // 手机系统语言 如英文en
    headers['lang'] = XmmPlatformUtils.systemLanguage; // 手机系统语言 如英文en
    if (XmmApis.isAuthorization(options.path)) {
      // ⚠️请注意：除登录接口和Config接口外，其余接口的Headers均需要附带token，格式为 Bearer拼接登录获取到的token
      headers['Authorization'] = 'Bearer${XmmAccountManager.instance.token}'; //
    }
    options.headers =  Map.from(headers).cast<String, dynamic>();
    super.onRequest(options, handler);
  }
}
